<template>
  <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item :to="{ path: '/overview' }">
      <h3>首页</h3>
    </el-breadcrumb-item>

    <el-breadcrumb-item>
      <h3>自动化API接口测试</h3>
    </el-breadcrumb-item>
  </el-breadcrumb>

  <!-- 添加一个卡片  -->

  <el-row :gutter="20">
    <el-col :span="18" :offset="2">
      <div class="grid-content">
        <!-- <el-row>
            <el-button size="large" type="primary" @click="getMethod">Message</el-button>
            <el-button size="large" type="primary" @click="sendemail">邮件测试</el-button> 
            <el-button size="large" type="primary" @click="locust">locust测试</el-button> 
          </el-row> -->
        <el-row>
          <!-- <el-button size="large" type="primary" @click="celrytest">celery测试</el-button> -->
        </el-row>
      </div>
    </el-col>
  </el-row>

  <el-row>
    <div>
      <span>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      </span>
    </div>
  </el-row>

  <el-form :model="apiformmodel" label-width="100px" ref='formRef' :rules="rules">
    <el-row class="el-row1" :gutter="20">
      <el-col :span="18" :offset="2">

        <el-form-item label="测试账户" prop="name">
          <el-input v-model="apiformmodel.name" placeholder="请输入用户名" style="width: 80%;" />
        </el-form-item>

      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="18" :offset="2">
        <el-form-item label="测试密码" prop="passwd">
          <el-input v-model="apiformmodel.passwd" placeholder="请输入密码" style="width: 80%;" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="18" :offset="2">
        <el-form-item label="环境选择" prop="environment">
          <el-select v-model="apiformmodel.environment" placeholder="please choose" style="width: 80%;">
            <el-option label="testsss环境" value="https://testsss.xlvren.com" />
            <el-option label="生产环境" value="https://www.xlvren.com" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="18" :offset="2">
        <el-form-item label="选择执行用例" prop="script">
          <el-select v-model="apiformmodel.scrlist" placeholder="Please choose scriptlist" style="width: 80%;">
            <el-option v-for="item in testdata" :value="item" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- options 是要传入dict类型  -->
    <el-row :gutter="20">
      <el-col :span="18" :offset="12">
        <el-form-item>
          <el-button type="primary" @click="onSubmit">执行测试</el-button>
          <el-button type="primary" @click="onreset">重置</el-button>
          <el-button type="primary" @click="downloadFile">下载API接口模板</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="2"></el-col>
    </el-row>

  </el-form>

  <el-divider />

  <!-- 列表 -->
  <el-row class="el-row" :gutter="20">
    <el-col :span="20" :offset="2">

      <!-- <el-table :data="tasklisttable" :border="true" style="width: 100%" stripe :table-layout="tableLayout">
       data  tasklisttable 返回的数据 要和每个列表中的 prop 数据一致才可以正常显示
        <el-table-column prop="pk" label="ID" width="70" />
        <el-table-column prop="fields.taskid" label="任务ID" width="300" />
        <el-table-column prop="fields.status" label="当前状态" width="160" />

        <el-table-column prop="fields.create_timestamp" label="创建时间" width="260" />
        <el-table-column prop="fields.flag" label="操作类型" width="140" />
        <el-table-column prop="fields.update_time" label="更新时间" />
      </el-table> -->



      <el-table :data="tasklisttable" :border="true" style="width: 100%" stripe :table-layout="tableLayout">
        <!-- data  tasklisttable 返回的数据 要和每个列表中的 prop 数据一致才可以正常显示-->
        <el-table-column prop="pk" label="ID" width="70" />
        <el-table-column prop="fields.taskid" label="任务ID" width="300" />
        <el-table-column prop="fields.status" label="当前状态" width="160" />

        <el-table-column prop="fields.create_timestamp" label="创建时间" width="260" />
        <el-table-column prop="fields.res_url" label="结果存储" />

        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <!-- <el-button size="small" type="danger" @click="querey_taskid(scope.$taskid)">
                            查询
                        </el-button> -->

            <el-button size="small" type="danger" @click="down(scope.row.fields.taskid)">
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-col>
  </el-row>


</template>

<script setup>

//ref() 函数用来根据给定的值创建一个响应式的数据对象，
// ref() 函数调用的返回值是一个对象，这个对象上只包含一个 .value 属性
//   1、scope.$index 代表拿到每一行的index
// 2、scope.row代表拿到每一行的数据
//    响应式数据  ref
import { ref, reactive } from 'vue'
import { scriptlist, taskupstatus, writeconf, taskquery, downloadapi, chosetest } from '../api/workers'
import dayjs from 'dayjs'
import { ArrowRight } from '@element-plus/icons-vue'     //图标
import { create } from 'lodash';
import { ElMessage } from 'element-plus';

// 设置表格单元、行和列的布局方式 ,也可以直接写 tableLayout ="fixed"或者是"auto"
const tableLayout = ref('auto')

// form表单初始化数据 
const apiformmodel = reactive({
  name: '15039508071',
  passwd: '123456',
  environment: '',
  scrlist: '',

})

// 任务列表
const tasklisttable = ref([])

// 后台返回的数据 
const testdata = ref({})
const tableData = ref([])
// form表单的校验
const formRef = ref(null)

// 校验规则   prop 校验 
const rules = reactive({
  name: [{ required: true, message: "必须填写", trigger: 'blur' }],
  passwd: [{ required: true, message: "必须填写", trigger: 'blur' }],
  environment: [{ required: true, message: '请选择测试环境', trigger: 'blur', }],
  scrlist: [{ required: true, message: '请选择测试脚本', trigger: 'blur', }]
})

// 获取待测试脚本数据文件
function getscript() {
  scriptlist().then(res => {
    console.log(res.data)
    testdata.value = res.data.msg

  })
}

// 执行选择接口测试
function onSubmit() {
  console.log('onSubmit 规则没有问题后, 进行接口测试');
  // 用户名和密码,写入到配置文件中, 根据选择的测试环境 ,执行的测试用例 ,执行测试 
  // 1.写入到配置文件
  formRef.value.validate(isValid => {
    if (isValid) {
      console.log(formRef.value);
      console.log("校验下数据,没有问题,执行下一步 ");
      // form表单中数据传参数就是下面的apiformmodel的对象 
      console.log(apiformmodel.environment, apiformmodel.passwd, apiformmodel.name, apiformmodel.scrlist);
      writeconf(apiformmodel).then(res => {
        //写入成功之后 ,接口测试开始读取配置文件 ,2 执行测试用例
        console.log("写成配置文件成功！");

        // 开始业务请求执行
        chosetest().then(res => {
          ElMessage({
            message: "已经开始执行自动化测试，执行完成后会自动发送邮件请注意查收！",
            type: 'info'
          })

        })


      }).catch(
        console.log("error")
      )


      // 重置选择的数据 
      apiformmodel.environment = ref('')
      apiformmodel.scrlist = ref('')

      // 刷新下任务列表 
      gettasklist()

    }
  })
}

// 重置 
function onreset() {
  apiformmodel.environment = ""
  apiformmodel.scrlist = ref('')
  // apiformmodel.name = ""
  // apiformmodel.passwd = ""

}

// 下载文件
const downloadFile = () => {
  console.log('dowload downloadFile !');
  let params = {
    filename: "api_demo.xlsx"
  }
  downloadapi(params).then(
    (res) => {
      // 打开下载的文件 总是提示文件内容损坏，不能打开 , 关闭掉 main。js中的mock相关的文件导入就可以了解决了
      let blob = new Blob([res.data], { "type": 'application/vnd.ms-excel;charset=utf-8' });

      const a = document.createElement('a');
      const url = URL.createObjectURL(blob);
      a.href = url;
      a.setAttribute('download', 'api_demo.xlsx'); // 设置下载文件名
      document.body.appendChild(a);      //将a标签添加到body当中
      a.click();
      document.body.removeChild(a);
      //释放内存
      window.URL.revokeObjectURL(url);


    }
  ).catch((e) => {
    ElMessage({
      message: "网络异常！",
      type: 'warning',
    })

  })

}




// 查看单个任务执行的结果反馈
function searchprocess(projectname, taskid) {
  console.log(projectname);
  console.log(taskid);

  taskstatus(projectname, taskid).then(
    res => {
      // 获取当前这个任务的状态, 然后更新到数据库中
      console.log(res.data.id)
      console.log(res.data.status)

      let result = res.data.status
      //单个任务更新数据库状态 
      taskupstatus(taskid, result).then(
        res => {
          console.log(res.data)
          if (res.data.code === 200) {
            // 更新查询的列表数据 
            gettask()
            ElMessage({
              type: "success",
              message: res.data.msg
            })
          } else {
            ElMessage({
              type: "error",
              message: res.data.msg
            })
          }
        }
      )
    }

  ).catch(
    console.log('catch')
  )
}

//删除行数据
const deleteRow = (index, $row) => {
  console.log($row);
  console.log($row.taskid);
  // tableData.value.splice(index, 1)
};

// 下载测试报告 
function downreport() {
  console.log('working');
}


//进入到界面默认执行里面的代码, 读取数据库中的记录文件
create()
{
  console.log(" 进入到这个页面就要执行")
  // 返回上传后的脚本列表
  getscript()
  // 查询到执行过的任务 
  // upTaskList()
  gettasklist()
}


// 执行任务的列表
function gettasklist() {
  taskquery().then(
    res => {
      console.log(res.data.msg);
      tasklisttable.value = res.data.msg
      console.log(tasklisttable.value);

    }
  )
}


const now = new Date();

//自动增加执行任务
const onAddItem = (action, code, task_id) => {
  now.setDate(now.getDate());
  tableData.value.push({
    date: dayjs(now).format('YYYY-MM-DD HH:MM'),
    project: action,
    taskid: task_id,
    result: code

  })
}


</script>

<style lang="less" scoped>
.box-card {
  height: 100%;
}

.el-row1 {
  margin-bottom: 20px;
}
</style>